<template>
	<view class="order-container">
		<!-- 顶部背景 -->
		<view class="header-bg">
			<!-- 导航栏 -->
			<view class="nav-bar">
				<image class="back" src="/static/images/白色左箭头.png" mode="" @click="goBack"></image>
				<text class="nav-title">确认订单</text>
			</view>
		</view>

		<!-- 订单信息卡片 -->
		<view class="order-card">
			<!-- 订单进度 -->
			<view class="progress-bar">
				<view class="progress-item active"
					:style="{ transform: currentStep === 1 ? 'scale(1.2)' : 'scale(1)' }">
					<view class="progress-circle">
						<image src="/static/home/wash/矩形 4@3x.png" mode="aspectFit" class="progress-bg"></image>
						<text class="progress-text">预约服务</text>
					</view>
				</view>
				<view class="progress-item">
					<view class="progress-circle" :style="{ transform: currentStep === 2 ? 'scale(1.3)' : 'scale(1)' }">
						<image src="/static/home/wash/矩形 4 拷贝 2@3x.png" mode="aspectFit" class="progress-bg"></image>
						<text class="progress-text">支付订单</text>
					</view>
				</view>
				<view class="progress-item">
					<view class="progress-circle" :style="{ transform: currentStep === 3 ? 'scale(1.2)' : 'scale(1)' }">
						<image src="/static/home/wash/矩形 4 拷贝@3x.png" mode="aspectFit" class="progress-bg"></image>
						<text class="progress-text">门店服务</text>
					</view>
				</view>
			</view>

			<view class="divider"></view>

			<!-- 店铺信息 -->
			<view class="shop-info">
				<image src="/static/home/wash/商家@3x.png" class="shop-icon"></image>
				<view class="shop-detail">
					<text class="shop-name">{{ merchantInfo?.name || '加载中...' }}</text>
					<text class="shop-address">{{ merchantInfo?.address || '加载中...' }}</text>
				</view>
			</view>

			<!-- 客户信息 -->
			<view class="customer-info">
				<view class="info-row">
					<image src="/static/home/wash/人员@3x.png" class="info-icon"></image>
					<text class="customer-name">{{ userDetail?.userName || '加载中...' }}</text>
					<text class="customer-phone">{{ userDetail?.phone || '加载中...' }}</text>
				</view>
			</view>

			<!-- 车辆信息 -->
			<view class="car-info" @click="selectChe">
				<view class="info-row">
					<image src="/static/home/wash/车辆-01@3x.png" class="info-icon"></image>
					<text class="car-detail">{{ selectedCar ? `${selectedCar.carBrand?.name} ${selectedCar.carType?.name}/${selectedCar.carNum}` : '请选择车辆' }}</text>
					<image src="/static/home/wash/收起箭头小@3x.png" class="info-icon arrow-icon"></image>
				</view>
			</view>

			<!-- 服务产品 -->
			<view class="service-section">
				<view class="section-header">
					<text class="section-title">服务产品</text>
					<text class="select-more">共选择1项服务产品</text>
				</view>
				<view class="service-item">
					<text class="service-name">{{ serviceInfo?.name || '加载中...' }}</text>
					<text class="service-price">¥{{ serviceInfo?.presentPrice || '0.00' }}</text>
				</view>
			</view>

			<!-- 优惠券 -->
			<view class="coupon-section" @click="selectCoupon">
				<view class="info-row">
					<image src="/static/home/wash/优惠券@3x.png" class="info-icon"></image>
					<text>代金券/优惠券</text>
					<view class="coupon-right">
						<text class="coupon-value">-10元</text>
						<image src="/static/home/wash/收起箭头小@3x.png" style="width: 18rpx; height: 30rpx;"
							class="info-icon">
						</image>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="service-contact" @click="contactService">
				<image src="/static/home/wash/客服@3x.png" class="service-icon"></image>
				<text>联系客服</text>
			</view>
			<view class="price-submit">
				<view class="total-price">
					<text>合计：</text>
					<text class="price">¥{{ totalPrice.toFixed(2) }}</text>
				</view>
				<button class="submit-btn" @click="submitOrder">提交订单</button>
			</view>
		</view>

		<!-- 支付密码弹窗 -->
		<uni-popup ref="payPopup" type="center">
			<view class="pay-popup">
				<view class="pay-header">
					<text class="close-icon" @click="closePayPopup">×</text>
					<text class="pay-title">请输入支付密码</text>
				</view>

				<view class="pay-content">
					<view class="merchant-name">{{ merchantInfo?.name || '加载中...' }}</view>
					<view class="pay-amount">¥{{ totalPrice.toFixed(2) }}</view>
				</view>

				<view class="payment-method">
					<text>支付方式</text>
					<text class="method-more">零钱 ></text>
				</view>

				<!-- 支付密码输入框 -->
				<view class="password-input">
					<input type="number" password maxlength="6" v-model="password" focus class="real-input" />
					<view class="fake-input">
						<view class="fake-item" v-for="(item, index) in 6" :key="index">
							<text v-if="password.length > index">•</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="servicePopup" type="bottom">
			<view class="service-popup">
				<view class="service-number">18642589456</view>
				<view class="action-buttons">
					<button class="action-btn copy-btn" @click="copyPhoneNumber">复制</button>
					<button class="action-btn cancel-btn" @click="closeServicePopup">取消</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted
	} from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';

	const currentStep = ref(1); // 1: 预约服务, 2: 支付订单, 3: 门店服务

	const payPopup = ref(null);
	const password = ref('');
	const servicePopup = ref(null);
	
	// 添加数据存储
	const merchantInfo = ref(null);
	const serviceInfo = ref(null);
	const totalPrice = ref(0);
	const userInfo = ref(null);
	const userDetail = ref(null);
	const selectedCar = ref(null);

	// 获取用户信息
	const getUserInfo = () => {
		try {
			const user = uni.getStorageSync('user');
			if (!user) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return null;
			}
			userInfo.value = user;
			return user;
		} catch (error) {
			console.error('获取用户信息失败:', error);
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			});
			return null;
		}
	};

	// 获取用户详细信息
	const fetchUserDetail = async (userId) => {
		try {
			const res = await uni.request({
				url: `http://localhost:9402/user/${userId}`,
				method: 'GET',
				header: {
					'Authorization': uni.getStorageSync('Token')
				}
			});
			
			if (res.data.code === 200 && res.data.data) {
				userDetail.value = res.data.data;
				return res.data.data;
			} else {
				uni.showToast({
					title: '获取用户详细信息失败',
					icon: 'none'
				});
				return null;
			}
		} catch (error) {
			console.error('获取用户详细信息失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
			return null;
		}
	};

	// 获取商户信息
	const fetchMerchantInfo = async (merchantId) => {
		try {
			const res = await uni.request({
				url: `http://localhost:9401/merchant/${merchantId}`,
				method: 'GET',
				header: {
					'Authorization': uni.getStorageSync('Token')
				}
			});
			
			if (res.data.code === 200 && res.data.data) {
				merchantInfo.value = res.data.data;
			} else {
				uni.showToast({
					title: '获取商户信息失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取商户信息失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
		}
	};

	// 获取服务信息
	const fetchServiceInfo = async (serviceId) => {
		try {
			const res = await uni.request({
				url: `http://localhost:9401/fuwudetails/${serviceId}`,
				method: 'GET',
				header: {
					'Authorization': uni.getStorageSync('Token')
				}
			});
			
			if (res.data.code === 200 && res.data.data) {
				serviceInfo.value = res.data.data;
				totalPrice.value = res.data.data.presentPrice;
			} else {
				uni.showToast({
					title: '获取服务信息失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取服务信息失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
		}
	};

	// 获取用户车辆列表
	const fetchUserCars = async (userId) => {
		try {
			const res = await uni.request({
				url: `http://localhost:9402/carinfo/user/${userId}`,
				method: 'GET',
				header: {
					'Authorization': uni.getStorageSync('Token')
				}
			});
			
			if (res.data.code === 200 && res.data.data) {
				const carList = res.data.data;
				if (carList.length === 0) {
					uni.showToast({
						title: '未找到可用车辆',
						icon: 'none'
					});
					return;
				}

				// 优先选择默认车辆
				let selectedCarData = carList.find(car => car.defaultCar === 1);
				
				// 如果没有默认车辆，选择第一辆车
				if (!selectedCarData) {
					selectedCarData = carList[0];
					uni.showToast({
						title: '未设置默认车辆，已选择第一辆车',
						icon: 'none',
						duration: 2000
					});
				}

				// 设置选中的车辆
				selectedCar.value = {
					id: selectedCarData.id,
					uid: selectedCarData.uid,
					typeId: selectedCarData.typeId,
					carNum: selectedCarData.carNum,
					defaultCar: selectedCarData.defaultCar,
					carUser: selectedCarData.carUser,
					carType: selectedCarData.carType,
					carBrand: selectedCarData.carBrand
				};

				// 存储到本地
				uni.setStorageSync('selectedCar', selectedCar.value);
			} else {
				uni.showToast({
					title: res.data.msg || '获取车辆列表失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取车辆列表失败:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
		}
	};

	// 页面加载时获取参数并请求数据
	onLoad(async (options) => {
		// 获取用户信息
		const currentUser = getUserInfo();
		if (!currentUser) {
			return;
		}

		// 获取用户详细信息
		const userDetailInfo = await fetchUserDetail(currentUser.id);
		if (!userDetailInfo) {
			return;
		}

		// 获取选中的车辆信息
		const car = uni.getStorageSync('selectedCar');
		if (car) {
			selectedCar.value = car;
		} else {
			// 如果没有选中的车辆，获取用户车辆列表并选择默认车辆
			await fetchUserCars(currentUser.id);
		}

		if (options.merchantId && options.serviceId) {
			fetchMerchantInfo(options.merchantId);
			fetchServiceInfo(options.serviceId);
		} else {
			uni.showToast({
				title: '参数不完整',
				icon: 'none'
			});
			setTimeout(() => {
				goBack();
			}, 1500);
		}
	});

	// 监听页面显示
	onShow(() => {
		// 每次页面显示时检查是否有新选择的车辆
		const car = uni.getStorageSync('selectedCar');
		if (car) {
			selectedCar.value = car;
		} else if (userInfo.value) {
			// 如果没有选中的车辆，获取用户车辆列表并选择默认车辆
			fetchUserCars(userInfo.value.id);
		}
	});

	const goBack = () => {
		uni.navigateBack();
	};
	const selectChe = () => {
		if (!userInfo.value || !userInfo.value.id) {
			uni.showToast({
				title: '用户信息不完整',
				icon: 'none'
			});
			return;
		}
		uni.navigateTo({
			url: `/pages/index/xiche/xichedetail/enterorder/selectche/selectche?userId=${userInfo.value.id}`
		});
	};
	const selectCoupon = () => {
		// 选择优惠券逻辑
		uni.navigateTo({
			url: '/pages/index/xiche/xichedetail/enterorder/youhuiquan/youhuiquan'
		});
	};

	// 显示支付弹窗
	const showPayPopup = () => {
		payPopup.value.open();
		currentStep.value = 2; // 切换到"支付订单"并放大
	};

	// 关闭支付弹窗
	const closePayPopup = () => {
		payPopup.value.close();
		password.value = ''; // 清空密码
		currentStep.value = 1; // 切换到"预约服务"并放大
	};

	// 修改提交订单方法
	const submitOrder = () => {
		currentStep.value = 2; // 切换到"支付订单"并放大
		showPayPopup();
	};

	// 监听密码输入
	watch(password, (newVal) => {
		if (newVal.length === 6) {
			// TODO: 处理支付逻辑
			console.log('支付密码输入完成');

			setTimeout(() => {
				closePayPopup();
			}, 1000);
			uni.navigateTo({
				url: '/pages/xiche/orderzhifu/orderzhifu'
			});
		}
	});

	// 显示客服弹出层
	const showServicePopup = () => {
		servicePopup.value.open();
	};

	// 关闭客服弹出层
	const closeServicePopup = () => {
		servicePopup.value.close();
	};

	// 复制电话号码
	const copyPhoneNumber = () => {
		uni.setClipboardData({
			data: '18642589456',
			success: () => {
				uni.showToast({
					title: '复制成功',
					icon: 'success'
				});
				closeServicePopup();
			}
		});
	};

	// 修改原有的底部按钮点击事件
	const contactService = () => {
		showServicePopup();
	};
</script>

<style scoped>
	.order-container {
		min-height: 100vh;
		background: #F8F8F8;
	}

	.header-bg {
		background: #4080FF;
		height: 240rpx;
		position: relative;
	}

	.back {
		position: absolute;
		left: 15px;
		top: 15px;
		width: 15px;
		height: 15px;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 88rpx;
		padding: 0 30rpx;
		color: #fff;
	}

	.right-icons {
		display: flex;
		gap: 20rpx;
	}

	.icon {
		width: 48rpx;
		height: 48rpx;
	}

	.order-card {
		margin: -140rpx 30rpx 0;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		position: relative;
		z-index: 1;
	}

	.progress-bar {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0 30rpx;
	}

	.progress-item {
		position: relative;
		width: 150rpx;
		height: 150rpx;
	}

	.progress-circle {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.progress-bg {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}

	.progress-text {
		position: relative;
		z-index: 1;
		font-size: 26rpx;
		color: #FFFFFF;
		text-align: center;
		line-height: 32rpx;
		padding: 0 20rpx;
	}

	.progress-item.active .progress-bg {
		transform: scale(1.1);
	}

	.divider {
		height: 1rpx;
		background: #EEEEEE;
		margin: 0 -30rpx 30rpx;
	}

	.shop-info {
		display: flex;
		align-items: center;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.shop-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.shop-detail {
		display: flex;
		flex-direction: column;
	}

	.shop-name {
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	.shop-address {
		font-size: 24rpx;
		color: #999;
	}

	.info-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.info-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.customer-phone {
		margin-left: auto;
		color: #999;
		font-size: 28rpx;
	}

	.arrow-right {
		margin-left: auto;
		color: #999;
		transform: rotate(-90deg);
	}

	.service-section {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.select-more {
		font-size: 24rpx;
		color: #999;
	}

	.service-item {
		display: flex;
		justify-content: space-between;
	}

	.service-price {
		color: #FF5252;
	}

	.coupon-right {
		margin-left: auto;
		display: flex;
		align-items: center;
	}

	.coupon-value {
		color: #FF5252;
		margin-right: 10rpx;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.service-contact {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
	}

	.service-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.price-submit {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.total-price {
		margin-right: 30rpx;
	}

	.price {
		color: #FF5252;
		font-weight: 500;
	}

	.submit-btn {
		background: #4080FF;
		color: #FFFFFF;
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
	}

	/* 支付弹窗样式 */
	.pay-popup {
		width: 600rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.pay-header {
		position: relative;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.close-icon {
		position: absolute;
		left: 30rpx;
		font-size: 40rpx;
		color: #999;
	}

	.pay-title {
		font-size: 32rpx;
		color: #333;
	}

	.pay-content {
		padding: 40rpx 30rpx;
		text-align: center;
	}

	.merchant-name {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.pay-amount {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
	}

	.payment-method {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #EEEEEE;
		font-size: 28rpx;
	}

	.method-more {
		color: #999;
	}

	.password-input {
		padding: 40rpx 60rpx;
		position: relative;
	}

	.real-input {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
		z-index: 1;
	}

	.fake-input {
		display: flex;
		justify-content: space-between;
		height: 100rpx;
	}

	.fake-item {
		width: 70rpx;
		height: 70rpx;
		border: 1rpx solid #DDDDDD;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	/* 客服弹出层样式 */
	.service-popup {
		background-color: #FFFFFF;
		padding: 40rpx;
		border-radius: 20rpx 20rpx 0 0;
	}

	.service-number {
		text-align: center;
		font-size: 40rpx;
		color: #333;
		margin-bottom: 40rpx;
	}

	.action-buttons {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.action-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 45rpx;
		font-size: 32rpx;
		border: none;
	}

	.copy-btn {
		background: #4080FF;
		color: #FFFFFF;
	}

	.cancel-btn {
		background: #F5F5F5;
		color: #333;
	}

	.car-detail {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.arrow-icon {
		width: 20rpx;
		height: 30rpx;
		margin-left: auto;
	}
</style>